package com.gears.tools;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.UUID;

import org.csource.test.FastDFSFile;
import org.csource.test.FileManager;

public class UpLoadFile {
	
	public static void upload(String filePath) throws Exception {
	  File content = new File(filePath);
	  FileInputStream fis = new FileInputStream(content);
	    byte[] file_buff = null;
	    if (fis != null) {
	    	int len = fis.available();
	    	file_buff = new byte[len];
	    	fis.read(file_buff);
	    }

	  FastDFSFile file = new FastDFSFile("520", file_buff, filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()));
	  String fileAbsolutePath = FileManager.upload(file);
	  System.out.println(fileAbsolutePath);
	  fis.close();
	}
	
	/**
	 * 获得指定文件的byte数组
	 * @param filePath 文件路劲
	 * @return byte[] 数组
	 * @throws Exception 
	 */
	public static byte[] getBytes(String filePath) throws Exception {
		byte[] buffer = null;
		File file = new File(filePath);
		if(!file.isFile()){
			throw new Exception("is not file exception");
		}
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
		byte[] b = new byte[1000];
		int n;
		while ((n = fis.read(b)) != -1) {
			bos.write(b, 0, n);
		}
		fis.close();
		bos.close();
		buffer = bos.toByteArray();
		return buffer;
	}

	/**
	 * 根据byte数组，生成文件
	 * @param bfile 保存的文件数组
	 * @param filePath 保存的文件路劲
	 * @param fileName 保存的文件全名称
	 * @return boolean
	 * @throws IOException 
	 */
	public static void getFile(byte[] bfile, String filePath, String fileName) throws IOException {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		File dir = new File(filePath);
		if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
													// if(!dir.exists()){//判断文件目录是否存在
			dir.mkdirs();
		}
		file = new File(filePath + "\\" + fileName);
		fos = new FileOutputStream(file);
		bos = new BufferedOutputStream(fos);
		bos.write(bfile);
		bos.close();
		fos.close();
	}
	
	public static void main(String[] args) {
		// String filePath = "D:\\doc.doc";
		// String filePath = "D:\\gif.gif";
		// String filePath = "D:\\66.swf";
		String filePath = "D:/1.pdf";
		String outFileName = UUID.randomUUID()
				+ filePath.substring(filePath.lastIndexOf("."),
						filePath.length());
		String outFilePath = "D:/test";
		
		try {
			getFile(getBytes(filePath), outFilePath, outFileName);
			System.out.println("file upload success ... ");
		} catch (Exception e) {
			System.out.println("file upload error ... ");
		}
		
	}
}
